import 'package:fish_redux/fish_redux.dart';
import 'package:wowhy/models/admin_user_info.dart';

import 'action.dart';
import 'state.dart';

Reducer<AdminUserListState> buildReducer() {
  return asReducer(
    <Object, Reducer<AdminUserListState>>{
      AdminUserListAction.init: _init,
      AdminUserListAction.search: _search,
      AdminUserListAction.refresh: _refresh,
      AdminUserListAction.fetch: _fetch,
    },
  );
}

AdminUserListState _init(AdminUserListState state, Action action) {
  final AdminUserListState newState = state.clone();
  return newState;
}

AdminUserListState _search(AdminUserListState state, Action action) {
  final AdminUserListState newState = state.clone();
  final String payload = action.payload ?? '';

  newState.query = payload;

  return newState;
}

AdminUserListState _refresh(AdminUserListState state, Action action) {
  final AdminUserListState newState = state.clone();
  final AdminUserListState payload = action.payload ?? AdminUserListState();

  newState.page = payload.page;
  newState.list = payload.list;
  newState.total = payload.total;

  newState.refreshController.refreshCompleted();
  if (payload.list.length < state.pageSize) {
    newState.refreshController.loadNoData();
  }

  return newState;
}

AdminUserListState _fetch(AdminUserListState state, Action action) {
  final AdminUserListState newState = state.clone();
  final AdminUserListState payload = action.payload ?? AdminUserListState();

  newState.page = payload.page;
  newState.list.addAll(payload.list);
  newState.total = payload.total;

  newState.refreshController.refreshCompleted();
  if (payload.list.isEmpty) {
    newState.refreshController.loadNoData();
  }

  return newState;
}
